/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.specific.condor;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.aist.gtrc.plus.reserve.*;
import jp.aist.gtrc.plus.scheduler.ScheduleStarter;
import jp.aist.gtrc.plus.scheduler.SchedulerOptions;
import jp.aist.gtrc.plus.scheduler.node.NodeAllocator;
import jp.aist.gtrc.plus.scheduler.node.NodeInfo;
import jp.aist.gtrc.plus.scheduler.node.NodeManager;
import jp.aist.gtrc.plus.scheduler.status.QInstanceStatus;
import jp.aist.gtrc.plus.scheduler.status.QueueStatus;
import jp.aist.gtrc.plus.scheduler.status.StatusManager;

public class CondorQbaseReserveManager extends QbaseReserveManager {

	public CondorQbaseReserveManager(NodeManager nodeMgr, ScheduleStarter starter, ReserveRecorder recorder, NodeAllocator nodeAllocator, StatusManager statusMgr, SchedulerOptions options) throws ReserveException {
		super(nodeMgr, starter, recorder, nodeAllocator, statusMgr, options);
	}

	@Override
	protected ReserveInfo newReserveInfo(ReserveId rsvId, ReserveRequest rsvReq, ReserveNodeSet rsvNodeSet) throws ReserveException {
		return new CondorQbaseReserveInfo(rsvId, rsvReq, rsvNodeSet);
	}

	private void suspendQInstance(QInstanceStatus qi) {
		Util.suspendQueue(qi.getQname(), qi.getQname());
	}

	private void resumeQInstance(QInstanceStatus qi) {
		Util.resumeQueue(qi.getQname(), qi.getQname());		
	}

	protected boolean hasJobToRun(QueueStatus q) {
		CondorQueueStatus status = (CondorQueueStatus)q;		
		return status.hasJobToRun();
	}

/*
	@Override
	protected void startReservePeriod(ReserveInfo info, Phase phase) throws ReserveException {
		Collection<NodeInfo> infos = info.getReservedNodeInfos();
		String [] users = info.getUsers();
		String postQueue = getPostQName(info);
		String preQueue =  getPreQName(info);
		String mainQueue = getMainQName(info);
		
		switch (phase){
		case ActivatePre:
			logger.debug("ActivatePre " + info.getReserveId());
			Util.activateQueue(preQueue, infos, users);
			break;
		case DelPreActMain:
			logger.debug("DelPreActMain " + info.getReserveId());
			Util.deactivateQueue(preQueue,infos);
			Util.activateQueue(mainQueue, infos, users);
			break;
		case ActivateMain:
			logger.debug("ActivateMain " + info.getReserveId());
			Util.activateQueue(mainQueue, infos, users);
			break;
		default:
			assert(false);
		    break;
		}
		
	}

	@Override
	protected void finishReservePeriod(ReserveInfo info, Phase phase) throws ReserveException {
		Collection<NodeInfo> infos = info.getReservedNodeInfos();
		String [] users = info.getUsers();
		String postQueue = getPostQName(info);
		String preQueue =  getPreQName(info);
		String mainQueue = getMainQName(info);

		switch (phase){
		case DelMainActPost:
			logger.debug("DelMainActPost " + info.getReserveId());
			Util.deactivateQueue(mainQueue,infos);
			Util.activateQueue(mainQueue, infos, users);
			break;
		case DeletePost:
			logger.debug("DeletePost " + info.getReserveId());
			Util.deactivateQueue(postQueue,infos);
			break;
		case DeleteMain:
			logger.debug("DeleteMain " + info.getReserveId());
			Util.deactivateQueue(mainQueue,infos);
			break;
		case DeleteAll:
			Util.deactivateQueue(preQueue,infos);
			Util.deactivateQueue(mainQueue,infos);
			Util.deactivateQueue(postQueue,infos);
			break;
		default:
			assert(false);
		    break;
		}
		
	}
*/

	private QueueStatus createQueueStatus(String name, Collection<NodeInfo> nodes){ 
		CondorQueueStatus status = new CondorQueueStatus(name);
		for (NodeInfo node: nodes){
			CondorQInstanceStatus qInstance = new CondorQInstanceStatus(status, node.getName(), true);
			status.add(qInstance);
		}
		return status;
	}

	private QueueStatus createQueueStatusFromString(String str){
		String[] tokens = str.split(" ");	
		CondorQueueStatus status = new CondorQueueStatus(tokens[0]);
		for (int i = 1; i < tokens.length; i++){
			CondorQInstanceStatus qInstance = new CondorQInstanceStatus(status, tokens[i], false);
			status.add(qInstance);
		}
		return status;
	}
	
	
	protected Collection<QueueStatus> getQueueStatus() throws ReserveException{
		Map<String, QueueStatus> map = new HashMap<String, QueueStatus>();
	
		ReserveTable table = this.getReserveTable();
		Collection<ReserveInfo> infos = table.getAllById();
		for (ReserveInfo info: infos){
			if (info.getStateStr().equals("Confirmed") || info.getStateStr().equals("Running")) {
				map.put(getMainQName(info), createQueueStatus(getMainQName(info), info.getReservedNodeInfos())); 
				if (info.getOptions().isMakePrePostQueue()){
					map.put(getPreQName(info), createQueueStatus(getPreQName(info), info.getReservedNodeInfos())); 
					map.put(getPostQName(info),createQueueStatus(getPostQName(info), info.getReservedNodeInfos())); 
				}
			}		
		}

		List<String> lines = Util.plusCondorStatus();
		for (String line: lines){
			QueueStatus qs = createQueueStatusFromString(line);
			map.put(qs.getName(), qs);
		}

		logger.debug("queueStatus");
		for (QueueStatus q: map.values())
			logger.debug("\t"+ q);
		logger.debug("queueStatus end");
		// 
		return map.values();
	}

	protected void suspendQInstances(Collection<QInstanceStatus> qinsList) {
		for (QInstanceStatus qins : qinsList) {
			suspendQInstance(qins);
		}
	}

	protected void resumeQInstances(Collection<QInstanceStatus> qinsList) {
		for (QInstanceStatus qins : qinsList) {
			resumeQInstance(qins);
		}
	}
	
	protected void resumeQueue(ReserveInfo info, String qname) throws ReserveException {
		Collection<NodeInfo> infos = info.getReservedNodeInfos();
		String [] users = info.getUsers();
		Util.activateQueue(qname, infos, users);
	}

	protected void deleteQueue(ReserveInfo info, String qname) throws ReserveException {
		Collection<NodeInfo> infos = info.getReservedNodeInfos();
		Util.deactivateQueue(qname, infos);
	}
	
}
